package com.zz.admin.auth.extension;

import com.alibaba.fastjson.JSON;
import com.zz.admin.auth.exception.CustomAccessDeniedException;
import com.zz.common.base.dto.ResultDto;
import com.zz.common.constants.ApiConstants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 拒绝访问时触发的处理器
 *
 * @author zl
 * @version 1.0
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String resultFail = ApiConstants.RESULT_FAIL;

        if (accessDeniedException instanceof CustomAccessDeniedException) {
            resultFail = ((CustomAccessDeniedException) accessDeniedException).getCode();
        }

        ResultDto resultDto = new ResultDto(resultFail, accessDeniedException.getMessage());
        String json = JSON.toJSONString(resultDto);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setStatus(ApiConstants.FORBIDDEN);
        response.getWriter().print(json);
    }

}
